<template>
  <div class="strategy-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h1>策略管理</h1>
        <p>管理和配置量化交易策略</p>
      </div>
      <div class="header-actions">
        <el-button type="primary" @click="handleCreateStrategy">
          <el-icon><Plus /></el-icon>
          新建策略
        </el-button>
        <el-button @click="handleImportStrategy">
          <el-icon><Upload /></el-icon>
          导入策略
        </el-button>
      </div>
    </div>

    <!-- 统计概览 -->
    <el-row :gutter="16" class="stats-row">
      <el-col :xs="24" :sm="12" :md="6" :lg="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-icon total">
              <el-icon><SetUp /></el-icon>
            </div>
            <div class="stats-info">
              <h3>总策略数</h3>
              <p class="stats-value">{{ totalStrategies }}</p>
              <span class="stats-change">+{{ newStrategiesThisMonth }}个本月新增</span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6" :lg="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-icon running">
              <el-icon><VideoPlay /></el-icon>
            </div>
            <div class="stats-info">
              <h3>运行中</h3>
              <p class="stats-value">{{ runningStrategies }}</p>
              <span class="stats-change">占总数{{ Math.round(runningStrategies/totalStrategies*100) }}%</span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6" :lg="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-icon profit">
              <el-icon><TrendCharts /></el-icon>
            </div>
            <div class="stats-info">
              <h3>盈利策略</h3>
              <p class="stats-value profit">{{ profitableStrategies }}</p>
              <span class="stats-change">胜率{{ Math.round(profitableStrategies/totalStrategies*100) }}%</span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6" :lg="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-icon performance">
              <el-icon><Trophy /></el-icon>
            </div>
            <div class="stats-info">
              <h3>平均收益率</h3>
              <p class="stats-value">{{ averageReturn }}%</p>
              <span class="stats-change">{{ monthlyReturnChange }} (本月)</span>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 策略列表 -->
    <el-card class="strategy-list-card">
      <template #header>
        <div class="card-header">
          <span class="card-title">策略列表</span>
          <div class="filter-controls">
            <el-select v-model="statusFilter" placeholder="策略状态" style="width: 120px; margin-right: 12px;">
              <el-option label="全部" value="all"></el-option>
              <el-option label="运行中" value="running"></el-option>
              <el-option label="暂停" value="paused"></el-option>
              <el-option label="停止" value="stopped"></el-option>
              <el-option label="异常" value="error"></el-option>
            </el-select>
            <el-select v-model="typeFilter" placeholder="策略类型" style="width: 140px; margin-right: 12px;">
              <el-option label="全部" value="all"></el-option>
              <el-option label="趋势跟踪" value="trend"></el-option>
              <el-option label="技术指标" value="technical"></el-option>
              <el-option label="网格交易" value="grid"></el-option>
              <el-option label="统计套利" value="arbitrage"></el-option>
              <el-option label="波动率" value="volatility"></el-option>
            </el-select>
            <el-input 
              v-model="searchKeyword" 
              placeholder="搜索策略名称" 
              style="width: 200px;"
              :prefix-icon="Search"
              clearable
            ></el-input>
          </div>
        </div>
      </template>

      <el-table 
        :data="filteredStrategies" 
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="name" label="策略名称" min-width="180">
          <template #default="{ row }">
            <div class="strategy-name-cell">
              <div class="strategy-icon">
                <el-icon v-if="row.type === 'trend'" color="#409eff"><TrendCharts /></el-icon>
                <el-icon v-else-if="row.type === 'technical'" color="#67c23a"><DataAnalysis /></el-icon>
                <el-icon v-else-if="row.type === 'grid'" color="#e6a23c"><Grid /></el-icon>
                <el-icon v-else-if="row.type === 'arbitrage'" color="#f56c6c"><ScaleToOriginal /></el-icon>
                <el-icon v-else color="#909399"><SetUp /></el-icon>
              </div>
              <div class="strategy-info">
                <div class="name">{{ row.name }}</div>
                <div class="type">{{ getStrategyTypeText(row.type) }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="symbol" label="交易对" width="120">
          <template #default="{ row }">
            <el-tag size="small">{{ row.symbol }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)" size="small">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="totalReturn" label="总收益率" width="120" sortable>
          <template #default="{ row }">
            <span :class="{ profit: row.totalReturn > 0, loss: row.totalReturn < 0 }">
              {{ row.totalReturn > 0 ? '+' : '' }}{{ row.totalReturn }}%
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="dailyReturn" label="今日收益" width="120" sortable>
          <template #default="{ row }">
            <span :class="{ profit: row.dailyReturn > 0, loss: row.dailyReturn < 0 }">
              {{ row.dailyReturn > 0 ? '+' : '' }}{{ row.dailyReturn }}%
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="trades" label="交易次数" width="100" sortable></el-table-column>
        <el-table-column prop="winRate" label="胜率" width="100" sortable>
          <template #default="{ row }">
            {{ row.winRate }}%
          </template>
        </el-table-column>
        <el-table-column prop="drawdown" label="最大回撤" width="120" sortable>
          <template #default="{ row }">
            <span class="loss">{{ row.drawdown }}%</span>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" sortable>
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button 
              v-if="row.status === 'stopped' || row.status === 'paused'" 
              type="success" 
              size="small" 
              @click="handleStartStrategy(row)"
            >
              启动
            </el-button>
            <el-button 
              v-if="row.status === 'running'" 
              type="warning" 
              size="small" 
              @click="handlePauseStrategy(row)"
            >
              暂停
            </el-button>
            <el-button 
              v-if="row.status === 'running' || row.status === 'paused'" 
              type="danger" 
              size="small" 
              @click="handleStopStrategy(row)"
            >
              停止
            </el-button>
            <el-dropdown @command="(command: string) => handleMoreActions(command, row)">
              <el-button size="small">
                更多<el-icon class="el-icon--right"><ArrowDown /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="view">查看详情</el-dropdown-item>
                  <el-dropdown-item command="edit">编辑策略</el-dropdown-item>
                  <el-dropdown-item command="backtest">回测分析</el-dropdown-item>
                  <el-dropdown-item command="clone">复制策略</el-dropdown-item>
                  <el-dropdown-item command="export">导出配置</el-dropdown-item>
                  <el-dropdown-item command="delete" divided>删除策略</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <div class="table-footer">
        <div class="batch-actions">
          <el-button 
            :disabled="selectedStrategies.length === 0"
            @click="handleBatchStart"
          >
            批量启动
          </el-button>
          <el-button 
            :disabled="selectedStrategies.length === 0"
            @click="handleBatchStop"
          >
            批量停止
          </el-button>
          <el-button 
            :disabled="selectedStrategies.length === 0"
            type="danger"
            @click="handleBatchDelete"
          >
            批量删除
          </el-button>
        </div>
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="strategies.length"
        />
      </div>
    </el-card>

    <!-- 编辑策略对话框 -->
    <el-dialog 
      v-model="editDialogVisible" 
      title="编辑策略" 
      width="800px"
      @close="resetEditForm"
    >
      <el-form :model="editForm" :rules="createRules" ref="editFormRef" label-width="120px">
        <el-form-item label="策略名称" prop="name">
          <el-input v-model="editForm.name" placeholder="请输入策略名称"></el-input>
        </el-form-item>
        <el-form-item label="策略类型" prop="type">
          <el-select v-model="editForm.type" placeholder="请选择策略类型" style="width: 100%;">
            <el-option label="趋势跟踪" value="trend"></el-option>
            <el-option label="技术指标" value="technical"></el-option>
            <el-option label="网格交易" value="grid"></el-option>
            <el-option label="统计套利" value="arbitrage"></el-option>
            <el-option label="波动率策略" value="volatility"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="交易对" prop="symbol">
          <el-select v-model="editForm.symbol" placeholder="请选择交易对" style="width: 100%;" filterable>
            <el-option label="BTC/USDT" value="BTC/USDT"></el-option>
            <el-option label="ETH/USDT" value="ETH/USDT"></el-option>
            <el-option label="SOL/USDT" value="SOL/USDT"></el-option>
            <el-option label="BNB/USDT" value="BNB/USDT"></el-option>
            <el-option label="ADA/USDT" value="ADA/USDT"></el-option>
            <el-option label="DOT/USDT" value="DOT/USDT"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="初始资金" prop="initialCapital">
          <el-input-number 
            v-model="editForm.initialCapital" 
            :min="100" 
            :max="1000000"
            :step="100"
            style="width: 100%;"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="风险等级" prop="riskLevel">
          <el-radio-group v-model="editForm.riskLevel">
            <el-radio label="low">低风险</el-radio>
            <el-radio label="medium">中风险</el-radio>
            <el-radio label="high">高风险</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="策略描述" prop="description">
          <el-input 
            v-model="editForm.description" 
            type="textarea" 
            :rows="3"
            placeholder="请输入策略描述"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleConfirmEdit">确认保存</el-button>
      </template>
    </el-dialog>

    <!-- 回测分析对话框 -->
    <el-dialog 
      v-model="backtestDialogVisible" 
      title="回测分析" 
      width="1000px"
    >
      <div class="backtest-content">
        <el-row :gutter="20">
          <el-col :span="8">
            <h4>回测配置</h4>
            <el-form label-width="100px">
              <el-form-item label="回测期间">
                <el-date-picker
                  v-model="backtestDateRange"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  style="width: 100%"
                />
              </el-form-item>
              <el-form-item label="初始资金">
                <el-input-number v-model="backtestCapital" :min="1000" :max="1000000" style="width: 100%" />
              </el-form-item>
              <el-form-item label="手续费率">
                <el-input-number v-model="backtestFeeRate" :min="0" :max="1" :step="0.001" style="width: 100%" />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="runBacktest">开始回测</el-button>
                <el-button @click="backtestDialogVisible = false">关闭</el-button>
              </el-form-item>
            </el-form>
          </el-col>
          <el-col :span="16">
            <h4>回测结果</h4>
            <div v-if="backtestRunning" class="backtest-loading">
              <el-icon class="is-loading"><Loading /></el-icon>
              <span>正在运行回测...</span>
            </div>
            <div v-else-if="backtestResults" class="backtest-results">
              <el-descriptions :column="2" border>
                <el-descriptions-item label="总收益率">
                  <span :class="{ profit: backtestResults.totalReturn > 0, loss: backtestResults.totalReturn < 0 }">
                    {{ backtestResults.totalReturn > 0 ? '+' : '' }}{{ backtestResults.totalReturn }}%
                  </span>
                </el-descriptions-item>
                <el-descriptions-item label="年化收益率">{{ backtestResults.annualReturn }}%</el-descriptions-item>
                <el-descriptions-item label="最大回撤">
                  <span class="loss">{{ backtestResults.maxDrawdown }}%</span>
                </el-descriptions-item>
                <el-descriptions-item label="夏普比率">{{ backtestResults.sharpeRatio }}</el-descriptions-item>
                <el-descriptions-item label="胜率">{{ backtestResults.winRate }}%</el-descriptions-item>
                <el-descriptions-item label="交易次数">{{ backtestResults.totalTrades }}次</el-descriptions-item>
              </el-descriptions>
            </div>
            <div v-else class="backtest-placeholder">
              <el-empty description="请配置回测参数并开始回测" />
            </div>
          </el-col>
        </el-row>
      </div>
    </el-dialog>

    <!-- 复制策略对话框 -->
    <el-dialog 
      v-model="cloneDialogVisible" 
      title="复制策略" 
      width="600px"
    >
      <el-form :model="cloneForm" label-width="120px">
        <el-form-item label="新策略名称" required>
          <el-input v-model="cloneForm.name" placeholder="请输入新策略名称"></el-input>
        </el-form-item>
        <el-form-item label="复制内容">
          <el-checkbox-group v-model="cloneForm.copyItems">
            <el-checkbox label="config">策略配置</el-checkbox>
            <el-checkbox label="parameters">参数设置</el-checkbox>
            <el-checkbox label="riskSettings">风险设置</el-checkbox>
            <el-checkbox label="notifications">通知设置</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="初始状态">
          <el-radio-group v-model="cloneForm.initialStatus">
            <el-radio label="stopped">停止状态</el-radio>
            <el-radio label="testing">测试模式</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="cloneDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleConfirmClone">确认复制</el-button>
      </template>
    </el-dialog>

    <!-- 创建策略对话框 -->
    <el-dialog 
      v-model="createDialogVisible" 
      title="新建策略" 
      width="800px"
      @close="resetCreateForm"
    >
      <el-form :model="createForm" :rules="createRules" ref="createFormRef" label-width="120px">
        <el-form-item label="策略名称" prop="name">
          <el-input v-model="createForm.name" placeholder="请输入策略名称"></el-input>
        </el-form-item>
        <el-form-item label="策略类型" prop="type">
          <el-select v-model="createForm.type" placeholder="请选择策略类型" style="width: 100%;">
            <el-option label="趋势跟踪" value="trend"></el-option>
            <el-option label="技术指标" value="technical"></el-option>
            <el-option label="网格交易" value="grid"></el-option>
            <el-option label="统计套利" value="arbitrage"></el-option>
            <el-option label="波动率策略" value="volatility"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="交易对" prop="symbol">
          <el-select v-model="createForm.symbol" placeholder="请选择交易对" style="width: 100%;" filterable>
            <el-option label="BTC/USDT" value="BTC/USDT"></el-option>
            <el-option label="ETH/USDT" value="ETH/USDT"></el-option>
            <el-option label="SOL/USDT" value="SOL/USDT"></el-option>
            <el-option label="BNB/USDT" value="BNB/USDT"></el-option>
            <el-option label="ADA/USDT" value="ADA/USDT"></el-option>
            <el-option label="DOT/USDT" value="DOT/USDT"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="初始资金" prop="initialCapital">
          <el-input-number 
            v-model="createForm.initialCapital" 
            :min="100" 
            :max="1000000"
            :step="100"
            style="width: 100%;"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="风险等级" prop="riskLevel">
          <el-radio-group v-model="createForm.riskLevel">
            <el-radio label="low">低风险</el-radio>
            <el-radio label="medium">中风险</el-radio>
            <el-radio label="high">高风险</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="策略描述" prop="description">
          <el-input 
            v-model="createForm.description" 
            type="textarea" 
            :rows="3"
            placeholder="请输入策略描述"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="createDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleConfirmCreate">确认创建</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getStrategies, updateStrategy, createStrategy, deleteStrategy, type Strategy } from '@/mock/strategyData';
import {
  Plus,
  Upload,
  SetUp,
  VideoPlay,
  TrendCharts,
  Trophy,
  Search,
  DataAnalysis,
  Grid,
  ScaleToOriginal,
  ArrowDown,
  Loading
} from '@element-plus/icons-vue';

const router = useRouter();

// 界面状态
const currentPage = ref(1);
const pageSize = ref(20);
const selectedStrategies = ref<any[]>([]);
const createDialogVisible = ref(false);
const createFormRef = ref();

// 编辑策略状态
const editDialogVisible = ref(false);
const editFormRef = ref();
const currentEditingStrategy = ref<any>(null);

// 回测分析状态
const backtestDialogVisible = ref(false);
const backtestRunning = ref(false);
const backtestResults = ref<any>(null);
const backtestDateRange = ref<string[]>([]);
const backtestCapital = ref(50000);
const backtestFeeRate = ref(0.001);

// 复制策略状态
const cloneDialogVisible = ref(false);
const currentCloneStrategy = ref<any>(null);

// 筛选状态
const statusFilter = ref('all');
const typeFilter = ref('all');
const searchKeyword = ref('');

// 统计数据
const totalStrategies = ref(12);
const runningStrategies = ref(8);
const profitableStrategies = ref(9);
const newStrategiesThisMonth = ref(3);
const averageReturn = ref(15.6);
const monthlyReturnChange = ref('+2.3%');

// 创建策略表单
const createForm = ref({
  name: '',
  type: '',
  symbol: '',
  initialCapital: 10000,
  riskLevel: 'medium',
  description: ''
});

// 编辑策略表单
const editForm = ref({
  name: '',
  type: '',
  symbol: '',
  initialCapital: 10000,
  riskLevel: 'medium',
  description: ''
});

// 复制策略表单
const cloneForm = ref({
  name: '',
  copyItems: ['config', 'parameters'],
  initialStatus: 'stopped'
});

const createRules = {
  name: [
    { required: true, message: '请输入策略名称', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择策略类型', trigger: 'change' }
  ],
  symbol: [
    { required: true, message: '请选择交易对', trigger: 'change' }
  ],
  initialCapital: [
    { required: true, message: '请输入初始资金', trigger: 'blur' }
  ]
};

// 策略数据
const strategies = ref<Strategy[]>([]);
const loading = ref(false);

// 加载策略数据
const loadStrategies = async () => {
  try {
    loading.value = true;
    const data = await getStrategies();
    strategies.value = data;
    
    // 更新统计数据
    totalStrategies.value = data.length;
    runningStrategies.value = data.filter(s => s.status === 'running').length;
    profitableStrategies.value = data.filter(s => s.totalReturn > 0).length;
    
    ElMessage.success('策略数据加载成功');
  } catch (error) {
    ElMessage.error('加载策略数据失败: ' + error);
  } finally {
    loading.value = false;
  }
};

// 原有的硬编码数据已移至 mock/strategyData.ts
const oldStrategies = ref([
  {
    id: 1,
    name: 'BTC蜻蜓Dragonfly策略',
    type: 'trend',
    symbol: 'BTC/USDT',
    status: 'running',
    totalReturn: 12.34, // 保守的年化收益
    dailyReturn: 0.38,
    trades: 89,
    winRate: 58.4, // 真实的趋势策略胜率
    drawdown: -15.2, // 更真实的回撤
    initialCapital: 50000,
    currentCapital: 56170,
    createTime: '2024-01-15 09:30:00',
    updateTime: '2024-02-20 14:23:15',
    riskLevel: 'medium',
    description: '基于蜻蜓Doji反转信号，结合RSI超卖确认入场，适合4H-1D时间框架',
    sharpeRatio: 1.45,
    maxRunup: 22.1,
    avgTradeReturn: 1.2,
    volatility: 18.5
  },
  {
    id: 2,
    name: 'ETH MACD背离策略',
    type: 'technical',
    symbol: 'ETH/USDT',
    status: 'paused',
    totalReturn: -3.21, // 技术指标策略可能亏损
    dailyReturn: 0.0,
    trades: 156,
    winRate: 51.3, // 略超过50%
    drawdown: -18.7,
    initialCapital: 30000,
    currentCapital: 29037,
    createTime: '2024-01-20 16:45:00',
    updateTime: '2024-02-19 10:15:30',
    riskLevel: 'high',
    description: 'MACD柱状图背离+成交量确认，专注ETH短期技术面反转机会',
    sharpeRatio: 0.23,
    maxRunup: 8.9,
    avgTradeReturn: -0.2,
    volatility: 24.3
  },
  {
    id: 3,
    name: 'BTC网格2.0策略',
    type: 'grid',
    symbol: 'BTC/USDT',
    status: 'running',
    totalReturn: 8.67, // 网格策略稳定收益
    dailyReturn: 0.23,
    trades: 445, // 网格策略交易频繁
    winRate: 64.7, // 网格胜率较高
    drawdown: -6.8, // 网格回撤相对较小
    initialCapital: 100000,
    currentCapital: 108670,
    createTime: '2024-01-10 11:20:00',
    updateTime: '2024-02-20 16:45:22',
    riskLevel: 'low',
    description: '动态网格间距调整，智能止盈止损，适合震荡行情自动化交易',
    sharpeRatio: 2.1,
    maxRunup: 12.4,
    avgTradeReturn: 0.19,
    volatility: 8.2
  },
  {
    id: 4,
    name: 'SOL高频动量策略',
    type: 'volatility',
    symbol: 'SOL/USDT',
    status: 'running',
    totalReturn: 15.89, // 高频策略收益适中
    dailyReturn: 0.67,
    trades: 1247, // 高频交易次数多
    winRate: 55.2, // 高频胜率不会太高
    drawdown: -12.4,
    initialCapital: 25000,
    currentCapital: 28972,
    createTime: '2024-01-25 13:15:00',
    updateTime: '2024-02-20 15:30:45',
    riskLevel: 'high',
    description: 'SOL 1分钟K线动量捕捉，基于订单流分析和Level2深度数据',
    sharpeRatio: 1.32,
    maxRunup: 24.6,
    avgTradeReturn: 0.13,
    volatility: 28.7
  },
  {
    id: 5,
    name: 'BNB均线多空策略',
    type: 'technical',
    symbol: 'BNB/USDT',
    status: 'error',
    totalReturn: -1.67, // API异常导致亏损
    dailyReturn: -0.05,
    trades: 34,
    winRate: 47.1, // 异常情况胜率下降
    drawdown: -8.9,
    initialCapital: 20000,
    currentCapital: 19666,
    createTime: '2024-02-05 09:00:00',
    updateTime: '2024-02-18 08:22:10',
    riskLevel: 'medium',
    description: 'EMA21/55双均线系统，目前遇到币安API频次限制异常',
    sharpeRatio: -0.45,
    maxRunup: 4.2,
    avgTradeReturn: -0.49,
    volatility: 16.8
  },
  {
    id: 6,
    name: 'ADA突破回踩策略',
    type: 'trend',
    symbol: 'ADA/USDT',
    status: 'running',
    totalReturn: 7.23, // 小币种策略收益保守
    dailyReturn: 0.31,
    trades: 67,
    winRate: 56.7,
    drawdown: -11.5,
    initialCapital: 15000,
    currentCapital: 16084,
    createTime: '2024-01-30 14:22:00',
    updateTime: '2024-02-20 13:18:35',
    riskLevel: 'medium',
    description: 'ADA关键阻力位突破后回踩确认，严格风控1:2盈亏比',
    sharpeRatio: 1.15,
    maxRunup: 15.3,
    avgTradeReturn: 1.08,
    volatility: 19.4
  },
  {
    id: 7,
    name: 'CEX套利机器人',
    type: 'arbitrage',
    symbol: 'USDT',
    status: 'stopped',
    totalReturn: 4.56, // 套利策略低风险低收益
    dailyReturn: 0.0,
    trades: 289,
    winRate: 78.2, // 套利胜率高
    drawdown: -2.1, // 套利回撤小
    initialCapital: 40000,
    currentCapital: 41824,
    createTime: '2024-01-12 10:30:00',
    updateTime: '2024-02-15 17:25:20',
    riskLevel: 'low',
    description: '币安-OKX-Bybit三角套利，因资金费率调整暂停运行',
    sharpeRatio: 3.2,
    maxRunup: 6.8,
    avgTradeReturn: 0.16,
    volatility: 2.8
  },
  {
    id: 8,
    name: 'BTC机器学习预测',
    type: 'technical',
    symbol: 'BTC/USDT',
    status: 'running',
    totalReturn: 18.45, // ML策略可能有较好收益
    dailyReturn: 0.74,
    trades: 167,
    winRate: 61.1, // ML胜率适中
    drawdown: -16.8,
    initialCapital: 80000,
    currentCapital: 94760,
    createTime: '2024-01-08 08:15:00',
    updateTime: '2024-02-20 16:58:12',
    riskLevel: 'high',
    description: 'LSTM神经网络+技术指标融合，实时特征工程和模型更新',
    sharpeRatio: 1.67,
    maxRunup: 28.3,
    avgTradeReturn: 1.1,
    volatility: 22.1
  },
  {
    id: 9,
    name: 'ETH-DeFi收益农场',
    type: 'grid',
    symbol: 'ETH/USDT',
    status: 'running',
    totalReturn: 11.23, // DeFi策略考虑Gas费用
    dailyReturn: 0.45,
    trades: 78, // DeFi操作频次较低
    winRate: 71.8, // LP收益策略胜率高
    drawdown: -9.2,
    initialCapital: 35000,
    currentCapital: 38930,
    createTime: '2024-01-18 15:45:00',
    updateTime: '2024-02-20 14:12:50',
    riskLevel: 'medium',
    description: 'Uniswap V3集中流动性+自动复投，动态调整价格区间',
    sharpeRatio: 1.89,
    maxRunup: 16.7,
    avgTradeReturn: 1.44,
    volatility: 12.3
  },
  {
    id: 10,
    name: 'SOL期现套利策略',
    type: 'arbitrage',
    symbol: 'SOL/USDT',
    status: 'paused',
    totalReturn: 6.78,
    dailyReturn: 0.0,
    trades: 156,
    winRate: 68.6, // 期现套利胜率较高
    drawdown: -4.3, // 对冲策略回撤小
    initialCapital: 18000,
    currentCapital: 19220,
    createTime: '2024-02-01 12:00:00',
    updateTime: '2024-02-18 11:30:25',
    riskLevel: 'low',
    description: 'SOL现货-永续合约价差套利，基差收敛自动平仓',
    sharpeRatio: 2.45,
    maxRunup: 9.1,
    avgTradeReturn: 0.43,
    volatility: 5.2
  },
  {
    id: 11,
    name: 'BNB事件驱动策略',
    type: 'technical',
    symbol: 'BNB/USDT',
    status: 'running',
    totalReturn: 9.34,
    dailyReturn: 0.42,
    trades: 23, // 事件驱动交易频次低
    winRate: 65.2,
    drawdown: -7.8,
    initialCapital: 22000,
    currentCapital: 24054,
    createTime: '2024-01-22 16:30:00',
    updateTime: '2024-02-20 15:45:18',
    riskLevel: 'medium',
    description: '币安Launchpad、燃烧销毁等事件驱动，新闻情感分析辅助',
    sharpeRatio: 1.56,
    maxRunup: 13.2,
    avgTradeReturn: 4.06,
    volatility: 14.7
  },
  {
    id: 12,
    name: 'Multi-DEX聚合套利',
    type: 'arbitrage',
    symbol: 'USDC',
    status: 'stopped',
    totalReturn: 2.89, // DEX套利收益较低但稳定
    dailyReturn: 0.0,
    trades: 234,
    winRate: 82.1, // DEX套利胜率很高
    drawdown: -1.8, // MEV保护回撤极小
    initialCapital: 12000,
    currentCapital: 12347,
    createTime: '2024-02-08 09:15:00',
    updateTime: '2024-02-16 14:20:30',
    riskLevel: 'low',
    description: 'Uniswap-Sushiswap-PancakeSwap价差套利，MEV保护机制',
    sharpeRatio: 4.1,
    maxRunup: 4.2,
    avgTradeReturn: 0.12,
    volatility: 1.4
  }
]);

// 计算过滤后的策略列表
const filteredStrategies = computed(() => {
  let result = strategies.value;
  
  // 状态筛选
  if (statusFilter.value !== 'all') {
    result = result.filter(s => s.status === statusFilter.value);
  }
  
  // 类型筛选
  if (typeFilter.value !== 'all') {
    result = result.filter(s => s.type === typeFilter.value);
  }
  
  // 关键词搜索
  if (searchKeyword.value) {
    result = result.filter(s => 
      s.name.toLowerCase().includes(searchKeyword.value.toLowerCase())
    );
  }
  
  return result;
});

// 工具函数
const getStrategyTypeText = (type: string) => {
  const typeMap: Record<string, string> = {
    trend: '趋势跟踪',
    technical: '技术指标',
    grid: '网格交易',
    arbitrage: '统计套利',
    volatility: '波动率策略'
  };
  return typeMap[type] || type;
};

const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    running: '运行中',
    paused: '暂停',
    stopped: '停止',
    error: '异常'
  };
  return statusMap[status] || status;
};

const getStatusTagType = (status: string) => {
  const typeMap: Record<string, string> = {
    running: 'success',
    paused: 'warning',
    stopped: 'info',
    error: 'danger'
  };
  return typeMap[status] || 'info';
};

const formatDate = (dateStr: string) => {
  return new Date(dateStr).toLocaleString('zh-CN');
};

// 事件处理函数
const handleCreateStrategy = () => {
  createDialogVisible.value = true;
};

const handleImportStrategy = () => {
  ElMessage.info('导入策略功能开发中...');
};

const handleSelectionChange = (selection: any[]) => {
  selectedStrategies.value = selection;
};

const handleStartStrategy = (strategy: any) => {
  ElMessageBox.confirm(`确认启动策略 "${strategy.name}"？`, '确认操作', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    strategy.status = 'running';
    ElMessage.success('策略启动成功');
  });
};

const handlePauseStrategy = (strategy: any) => {
  strategy.status = 'paused';
  ElMessage.success('策略已暂停');
};

const handleStopStrategy = (strategy: any) => {
  ElMessageBox.confirm(`确认停止策略 "${strategy.name}"？`, '确认操作', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    strategy.status = 'stopped';
    ElMessage.success('策略已停止');
  });
};

const handleMoreActions = (command: string, strategy: any) => {
  switch (command) {
    case 'view':
      router.push(`/trading/strategy/${strategy.id}`);
      break;
    case 'edit':
      handleEditStrategy(strategy);
      break;
    case 'backtest':
      handleBacktestStrategy(strategy);
      break;
    case 'clone':
      handleCloneStrategy(strategy);
      break;
    case 'export':
      handleExportStrategy(strategy);
      break;
    case 'delete':
      ElMessageBox.confirm(`确认删除策略 "${strategy.name}"？`, '确认删除', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const index = strategies.value.findIndex(s => s.id === strategy.id);
        if (index > -1) {
          strategies.value.splice(index, 1);
          ElMessage.success('策略删除成功');
        }
      });
      break;
  }
};

// 编辑策略
const handleEditStrategy = (strategy: any) => {
  currentEditingStrategy.value = strategy;
  editForm.value = {
    name: strategy.name,
    type: strategy.type,
    symbol: strategy.symbol,
    initialCapital: strategy.initialCapital,
    riskLevel: strategy.riskLevel,
    description: strategy.description
  };
  editDialogVisible.value = true;
};

const resetEditForm = () => {
  editForm.value = {
    name: '',
    type: '',
    symbol: '',
    initialCapital: 10000,
    riskLevel: 'medium',
    description: ''
  };
  editFormRef.value?.resetFields();
  currentEditingStrategy.value = null;
};

const handleConfirmEdit = () => {
  editFormRef.value?.validate((valid: boolean) => {
    if (valid && currentEditingStrategy.value) {
      Object.assign(currentEditingStrategy.value, editForm.value);
      currentEditingStrategy.value.updateTime = new Date().toLocaleString('zh-CN');
      editDialogVisible.value = false;
      ElMessage.success('策略更新成功');
      resetEditForm();
    }
  });
};

// 回测分析
const handleBacktestStrategy = (strategy: any) => {
  backtestDateRange.value = [];
  backtestCapital.value = strategy.initialCapital;
  backtestResults.value = null;
  backtestRunning.value = false;
  backtestDialogVisible.value = true;
};

const runBacktest = () => {
  if (!backtestDateRange.value || backtestDateRange.value.length !== 2) {
    ElMessage.warning('请选择回测期间');
    return;
  }
  
  backtestRunning.value = true;
  
  // 模拟回测运行
  setTimeout(() => {
    backtestResults.value = {
      totalReturn: Math.random() * 50 - 10, // -10% 到 40%
      annualReturn: Math.random() * 60 - 15, // -15% 到 45%
      maxDrawdown: Math.random() * 20, // 0% 到 20%
      sharpeRatio: Math.random() * 2 + 0.5, // 0.5 到 2.5
      winRate: Math.random() * 40 + 40, // 40% 到 80%
      totalTrades: Math.floor(Math.random() * 500) + 100 // 100 到 600
    };
    backtestRunning.value = false;
    ElMessage.success('回测完成');
  }, 3000);
};

// 复制策略
const handleCloneStrategy = (strategy: any) => {
  currentCloneStrategy.value = strategy;
  cloneForm.value = {
    name: `${strategy.name} - 副本`,
    copyItems: ['config', 'parameters'],
    initialStatus: 'stopped'
  };
  cloneDialogVisible.value = true;
};

const handleConfirmClone = () => {
  if (!cloneForm.value.name.trim()) {
    ElMessage.warning('请输入新策略名称');
    return;
  }
  
  if (currentCloneStrategy.value) {
    const newStrategy = {
      ...currentCloneStrategy.value,
      id: Date.now(),
      name: cloneForm.value.name,
      status: cloneForm.value.initialStatus,
      totalReturn: 0,
      dailyReturn: 0,
      trades: 0,
      currentCapital: currentCloneStrategy.value.initialCapital,
      createTime: new Date().toLocaleString('zh-CN'),
      updateTime: new Date().toLocaleString('zh-CN')
    };
    
    strategies.value.unshift(newStrategy);
    totalStrategies.value++;
    cloneDialogVisible.value = false;
    ElMessage.success('策略复制成功');
  }
};

// 导出策略
const handleExportStrategy = (strategy: any) => {
  const config = {
    name: strategy.name,
    type: strategy.type,
    symbol: strategy.symbol,
    initialCapital: strategy.initialCapital,
    riskLevel: strategy.riskLevel,
    description: strategy.description,
    exportTime: new Date().toLocaleString('zh-CN')
  };
  
  const dataStr = JSON.stringify(config, null, 2);
  const dataBlob = new Blob([dataStr], { type: 'application/json' });
  const url = URL.createObjectURL(dataBlob);
  const link = document.createElement('a');
  link.href = url;
  link.download = `${strategy.name}_配置.json`;
  link.click();
  URL.revokeObjectURL(url);
  
  ElMessage.success('策略配置导出成功');
};

const handleBatchStart = () => {
  ElMessage.info('批量启动功能开发中...');
};

const handleBatchStop = () => {
  ElMessage.info('批量停止功能开发中...');
};

const handleBatchDelete = () => {
  ElMessageBox.confirm(`确认删除选中的 ${selectedStrategies.value.length} 个策略？`, '确认删除', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    selectedStrategies.value.forEach(strategy => {
      const index = strategies.value.findIndex(s => s.id === strategy.id);
      if (index > -1) {
        strategies.value.splice(index, 1);
      }
    });
    selectedStrategies.value = [];
    ElMessage.success('批量删除成功');
  });
};

const resetCreateForm = () => {
  createForm.value = {
    name: '',
    type: '',
    symbol: '',
    initialCapital: 10000,
    riskLevel: 'medium',
    description: ''
  };
  createFormRef.value?.resetFields();
};

const handleConfirmCreate = () => {
  createFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      try {
        loading.value = true;
        const newStrategyData = {
          ...createForm.value,
          status: 'stopped' as const,
          totalReturn: 0,
          dailyReturn: 0,
          trades: 0,
          winRate: 0,
          drawdown: 0,
          currentCapital: createForm.value.initialCapital,
          sharpeRatio: 0,
          maxRunup: 0,
          avgTradeReturn: 0,
          volatility: 0,
          indicators: {
            buy: {
              dragonfly: { enabled: false, timeframe: '4h', shadowRatio: 3.0 },
              rsi: { enabled: false, period: 14, oversold: 30, confirm: 35 },
              volume: { enabled: false, multiplier: 1.5, period: 20 },
              ma: { enabled: false, short: 20, long: 50, position: 'both' },
              macd: { enabled: false, fast: 12, slow: 26, signal: 9 },
              bollinger: { enabled: false, period: 20, stdDev: 2 },
              stochastic: { enabled: false, period: 14, smoothK: 3, smoothD: 3 }
            },
            sell: {
              takeProfit: { enabled: true, percentage: 5.0, trailing: false },
              stopLoss: { enabled: true, percentage: 3.0, dynamic: false },
              rsi: { enabled: false, period: 14, overbought: 70, duration: 2 },
              gravestone: { enabled: false, timeframe: '4h', shadowRatio: 3.0 },
              macd: { enabled: false, divergence: false },
              bollinger: { enabled: false, upperBand: false }
            }
          },
          riskConfig: {
            maxPosition: 50,
            maxSingleTrade: 10,
            riskFactor: 1.0,
            dailyMaxLoss: 5,
            maxConsecutiveLoss: 3,
            drawdownAlert: 10,
            dailyMaxTrades: 10,
            tradeInterval: 30,
            cooldownPeriod: 60
          }
        };
        
        await createStrategy(newStrategyData);
        await loadStrategies(); // 重新加载数据
        createDialogVisible.value = false;
        ElMessage.success('策略创建成功');
        resetCreateForm();
      } catch (error) {
        ElMessage.error('创建策略失败: ' + error);
      } finally {
        loading.value = false;
      }
    }
  });
};

onMounted(() => {
  // 页面初始化 - 加载策略数据
  loadStrategies();
});
</script>

<style lang="scss" scoped>
.strategy-page {
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 24px;

    .header-left {
      h1 {
        margin: 0 0 8px 0;
        font-size: 28px;
        font-weight: 600;
        color: var(--el-text-color-primary);
      }

      p {
        margin: 0;
        color: var(--el-text-color-regular);
        font-size: 16px;
      }
    }

    .header-actions {
      display: flex;
      gap: 12px;
    }
  }

  .stats-row {
    margin-bottom: 24px;

    .el-col {
      margin-bottom: 16px;
    }
  }

  .stats-card {
    height: 100%;
    transition: all 0.3s ease;
    border: none;

    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 8px 30px rgba(0, 0, 0, 0.08);
    }

    .stats-content {
      display: flex;
      align-items: center;
      padding: 0;

      .stats-icon {
        width: 56px;
        height: 56px;
        border-radius: 12px;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 16px;

        &.total {
          background: linear-gradient(135deg, #409eff, #66b1ff);
          color: white;
        }

        &.running {
          background: linear-gradient(135deg, #67c23a, #85ce61);
          color: white;
        }

        &.profit {
          background: linear-gradient(135deg, #e6a23c, #eebe77);
          color: white;
        }

        &.performance {
          background: linear-gradient(135deg, #f56c6c, #f78989);
          color: white;
        }

        .el-icon {
          font-size: 24px;
        }
      }

      .stats-info {
        flex: 1;

        h3 {
          font-size: 14px;
          color: var(--el-text-color-regular);
          margin: 0 0 4px 0;
          font-weight: normal;
        }

        .stats-value {
          font-size: 24px;
          font-weight: 600;
          margin: 0 0 4px 0;
          color: var(--el-text-color-primary);

          &.profit {
            color: var(--el-color-success);
          }
        }

        .stats-change {
          font-size: 12px;
          color: var(--el-text-color-secondary);
        }
      }
    }
  }

  .strategy-list-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .card-title {
        font-size: 16px;
        font-weight: 600;
        color: var(--el-text-color-primary);
      }

      .filter-controls {
        display: flex;
        align-items: center;
        gap: 12px;
      }
    }

    .strategy-name-cell {
      display: flex;
      align-items: center;

      .strategy-icon {
        width: 36px;
        height: 36px;
        border-radius: 8px;
        background: var(--el-fill-color-light);
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 12px;

        .el-icon {
          font-size: 18px;
        }
      }

      .strategy-info {
        .name {
          font-weight: 600;
          font-size: 14px;
          color: var(--el-text-color-primary);
          margin-bottom: 2px;
        }

        .type {
          font-size: 12px;
          color: var(--el-text-color-secondary);
        }
      }
    }

    .profit {
      color: var(--el-color-success);
      font-weight: 600;
    }

    .loss {
      color: var(--el-color-danger);
      font-weight: 600;
    }

    .table-footer {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-top: 20px;
      padding-top: 20px;
      border-top: 1px solid var(--el-border-color-lighter);

      .batch-actions {
        display: flex;
        gap: 8px;
      }
    }
  }

  :deep(.el-table) {
    .el-table__row {
      &:hover {
        background-color: var(--el-fill-color-extra-light);
      }
    }

    .el-table__cell {
      padding: 12px 0;
    }
  }

  :deep(.el-dialog__body) {
    padding: 20px 20px 10px 20px;
  }

  :deep(.el-form-item) {
    margin-bottom: 22px;
  }

  // 回测分析样式
  .backtest-content {
    h4 {
      margin-bottom: 16px;
      color: #303133;
      font-weight: 500;
    }
  }

  .backtest-loading {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 200px;
    gap: 12px;
    color: #909399;
    
    .el-icon {
      font-size: 24px;
    }
  }

  .backtest-results {
    .profit {
      color: #67c23a;
    }
    
    .loss {
      color: #f56c6c;
    }
  }

  .backtest-placeholder {
    height: 200px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}

// 响应式设计
@media (max-width: 1200px) {
  .strategy-page {
    .page-header {
      flex-direction: column;
      align-items: flex-start;
      gap: 16px;

      .header-actions {
        align-self: flex-end;
      }
    }

    .stats-card {
      .stats-content {
        .stats-icon {
          width: 48px;
          height: 48px;

          .el-icon {
            font-size: 20px;
          }
        }

        .stats-info {
          .stats-value {
            font-size: 20px;
          }
        }
      }
    }
  }
}

@media (max-width: 768px) {
  .strategy-page {
    .page-header {
      .header-left {
        h1 {
          font-size: 24px;
        }

        p {
          font-size: 14px;
        }
      }

      .header-actions {
        flex-direction: column;
        width: 100%;

        .el-button {
          width: 100%;
        }
      }
    }

    .strategy-list-card {
      .card-header {
        flex-direction: column;
        align-items: flex-start;
        gap: 16px;

        .filter-controls {
          width: 100%;
          flex-direction: column;

          .el-select,
          .el-input {
            width: 100% !important;
          }
        }
      }

      .table-footer {
        flex-direction: column;
        gap: 16px;

        .batch-actions {
          width: 100%;
          flex-wrap: wrap;

          .el-button {
            flex: 1;
          }
        }
      }
    }

    .stats-card {
      .stats-content {
        .stats-icon {
          width: 44px;
          height: 44px;
          margin-right: 12px;

          .el-icon {
            font-size: 18px;
          }
        }

        .stats-info {
          .stats-value {
            font-size: 18px;
          }

          h3 {
            font-size: 13px;
          }
        }
      }
    }
  }
}
</style>
